import { cn } from "@/lib/utils";
import { Slot } from "@radix-ui/react-slot";
import { cva } from "class-variance-authority";
import { forwardRef, Ref } from "react";

interface BtnVariant {
  default: string;
  destructive: string;
  outline: string;
  secondary: string;
  ghost: string;
  link: string;
}

interface BtnSize {
  default: string;
  sm: string;
  lg: string;
  icon: string;
}

type BtnVariantType = {
  [key in keyof BtnVariant]: BtnVariant[key];
};

type BtnSizeType = {
  [key in keyof BtnSize]: BtnSize[key];
};

const defineClassName = cva(
  "inline-flex items-center justify-center rounded-md text-sm font-medium whitespace-nowrap ring-offset-background transition-colors focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:outline-none disabled:pointer-events-none disabled:opacity-50",
  {
    variants: {
      variant: {
        default:
          "bg-primary text-primary-foreground hover:bg-primary/90 active:scale-95 active:brightness-90",
        destructive:
          "bg-destructive text-destructive-foreground hover:bg-destructive/90",
        outline:
          "border border-input bg-background hover:bg-accent hover:text-accent-foreground",
        secondary:
          "bg-secondary text-secondary-foreground hover:bg-secondary/80",
        ghost: "hover:bg-accent hover:text-accent-foreground",
        link: "text-primary underline-offset-4 hover:underline",
      } as BtnVariantType,
      size: {
        default: "px-4 py-2",
        sm: "px-3 py-1",
        lg: "px-6 py-3",
        icon: "h-10 w-10",
      } as BtnSizeType,
    },
    defaultVariants: {
      variant: "default",
      size: "default",
    },
  },
);

// 定义 ButtonProps 接口来验证 props 类型

interface ButtonProps extends React.ButtonHTMLAttributes<HTMLButtonElement> {
  variant?: keyof BtnVariantType;
  size?: keyof BtnSizeType;
  asChild?: boolean;
}

const Button = forwardRef(
  (
    { className, variant, size, asChild = false, ...props }: ButtonProps,
    ref: Ref<HTMLButtonElement>,
  ) => {
    const Comp = asChild ? Slot : "button";
    return (
      <Comp
        className={cn(defineClassName({ variant, size, className }))}
        ref={ref}
        {...props}
      />
    );
  },
);
Button.displayName = "Button";
export { Button, defineClassName };
